/**
 * pipe.c : Pipe example
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


int main(int argc, char **argv)
{
	char *command1, *command2;
	int pfd[2];
	int status;

	if(argc < 3) {
		printf("Use %s <command1> <command2>\n\n", argv[0]);
		exit(EXIT_FAILURE);
	} else {
 		command1 = argv[1];
		command2 = argv[2];
	}


	/* Create pipes */
	if(pipe(pfd) < 0) {
		perror("Error on creating pipes!\n");
		exit(EXIT_FAILURE);
	}

	/* Redirect input and output */
	if( !fork() ) {
		if( !fork() ) {
			/* The father */
			wait(&status);
		} else {
			/* command 2 */
			close(0); /* input */
			dup(pfd[0]);
			close(pfd[1]);
			execve(command2, NULL, NULL);
		}

	} else {
		/* command 1*/
		close(1); /* output */
		dup(pfd[1]);
		close(pfd[0]);
		execve(command1, NULL, NULL);
	}

	return(EXIT_SUCCESS);
}


